package com.yupi.project.controller;

import cn.hutool.core.io.FileUtil;
import com.yupi.project.service.FileService;
import com.yupi.project.service.UserService;
import com.yupi.yuapicommon.model.common.BaseResponse;
import com.yupi.yuapicommon.model.common.BusinessException;
import com.yupi.yuapicommon.model.common.ErrorCode;
import com.yupi.yuapicommon.model.common.ResultUtils;
import com.yupi.yuapicommon.model.entity.User;
import com.yupi.yuapicommon.utils.ExcelUtils;
import com.zzsource.yuapicliensdk.model.response.ResultResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @description: 文件上传功能
 * @author SummerBird
 * @date 2024/2/19 11:16
 * @version 1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private UserService userService;

    private static final String TMP_PATH = "/usr/share/nginx/images/";

    /*
     * 1.准备文件存储目录
     * 2.获取文件名称
     * 3.利用工具API实现文件上传
     */
    @PostMapping("/upload/img1")
    @ApiOperation(value = "文件上传（不安全）")
    @Deprecated
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile fileImage, HttpServletRequest request) throws IllegalStateException, IOException {
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        File fileDir = new File(TMP_PATH);
        if(!fileDir.exists()) {
            //如果没有目录应该创建目录
            fileDir.mkdirs();
        }
        //获取图片名称
        String imgName = "tmp" + fileImage.getOriginalFilename();
        String path = TMP_PATH + imgName;
        //文件实现上传
        fileImage.transferTo(new File(path));
        String imgUrl = "http://39.108.117.235/localImage/" + imgName;
        log.info("图片url: " + imgUrl);
        return ResultUtils.success(imgUrl);
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload/img2")
    @ApiOperation(value = "文件上传-只支持jpg/png/gif（较安全）")
    public BaseResponse<String> fileUpload(@RequestPart("file") MultipartFile uploadFile, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return fileService.fileUpload(uploadFile);
    }

}
